# copy to jars storrage and run pythonw run_py_httpfileshare.py

from __future__ import with_statement

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from threading import Thread, Lock
import os

FNAME_2_BUFFER = {}

def rec(root, sub):
	file = os.path.join(root, sub)
	if os.path.isfile(file):
		FNAME_2_BUFFER[sub] = file
	else:
		for fileName in os.listdir(file):
			subsub = os.path.join(sub, fileName)
			rec(root, subsub)

def init(rootPath):
	rec(rootPath, "")

class InterHTTPServer(HTTPServer):
	def __init__(self, server_address, RequestHandlerClass):
		HTTPServer.__init__(self, server_address, RequestHandlerClass)
		self.__lock = Lock()
		with self.__lock:
			self.__isAlive = True

	def setIsAlive(self, isAlive):
		with self.__lock:
			self.__isAlive = isAlive

	def serve_forever(self):
		while True:
			self.handle_request()
			with self.__lock:
				if not self.__isAlive:
					break

class FileShareHandler(BaseHTTPRequestHandler):
	def do_GET(self):
		print "GET:\t\t", self.path
		if (self.path.endswith("index.html")):
			self.send_response(200)
			self.send_header("Content-type", "text/html")
			self.end_headers()
			pageHtml = "<html>Content:"
			for fname in FNAME_2_BUFFER.keys():
				name = fname.replace("\\", "/")
				pageHtml += '<br><a href="' + name + '">' + name + '</a>'
			pageHtml += "</html>"
			self.wfile.write(pageHtml)
		else:
			path = self.path.split("/")[1:]
			path = os.path.join(*path)
			if FNAME_2_BUFFER.has_key(path):
				self.wfile.write(open(FNAME_2_BUFFER[path], "rb").read())
			else:
				self.send_response(200)
				self.send_header("Content-type", "text/html")
				self.end_headers()
				self.wfile.write('<html><a href="index.html">Unknown page. Go to index.html</a></html>')

class ServerThread(Thread):
	def __init__ (self, server):
		Thread.__init__(self)
		self.__server = server

	def run(self):
		self.__server.serve_forever()
		print "stop server ... "
		server.socket.close()
		print "server was stopped"

def main():
	init(".")
	server = InterHTTPServer(("", 1234), FileShareHandler)
	print "start fileshare server ... "
	serverThread = ServerThread(server)
	serverThread.start()
	print "press enter to interrupt"
	raw_input()
	server.setIsAlive(False)

if __name__ == "__main__":
	main()
